//
//  HJRequestClosure.swift
//  SwfitBase
//
//  Created by rubick on 2023/1/16.
//

import Foundation
import Moya
import Alamofire

// MARK: endpointClosure
let hjEndpointClosure = { (target: TargetType) -> Endpoint in
    let url = target.baseURL.absoluteString + target.path
    var task = target.task
    // 通用参数处理👇👇👇
    let parameter = [String: Any]()    // 👈🏻 参数配置
    switch target.task {
        case .requestPlain:
            task = .requestParameters(parameters: parameter, encoding: URLEncoding.default)
        case .requestParameters(var parameters, let encoding):
            parameter.forEach { parameters[$0.key] = $0.value  }
            task = .requestParameters(parameters: parameters, encoding: encoding)
        default:
            break
    }
    var endpoint = Endpoint(
        url: url,
        sampleResponseClosure: { .networkResponse(200, target.sampleData) },
        method: target.method,
        task: task,
        httpHeaderFields: target.headers
    )
    // 请求头处理👇👇👇
//    endpoint = endpoint.adding(newHTTPHeaderFields: ["token": "xxx"])  // 👈🏻request headers
    return endpoint
}

// MARK: requestClosure
let hjRequestClosure = { (endpoint: Endpoint, closure: MoyaProvider.RequestResultClosure) -> Void in
    do {
        var urlRequest = try endpoint.urlRequest()
        urlRequest.timeoutInterval = 75
        closure(.success(urlRequest))
    } catch MoyaError.requestMapping(let url) {
        closure(.failure(MoyaError.requestMapping(url)))
    } catch MoyaError.parameterEncoding(let error) {
        closure(.failure(MoyaError.parameterEncoding(error)))
    } catch {
        closure(.failure(MoyaError.underlying(error, nil)))
    }
}

// MARK: StubClosure
let hjStubClosure =  { (target: TargetType) in
    return Moya.StubBehavior.never
}
let hjMockStubClosure = { (target: TargetType) in
    return Moya.StubBehavior.immediate  // 使用sampleData中返回的测试数据
}

// MARK: Plugin
// Loading plugin
let hjRequestActivityPlugin = NetworkActivityPlugin { change, target in
    switch change {
    case .began:
        print("-------> begin request")
    case .ended:
        print("-------> end request")
    }
}
// Log Plugin
let hjRequestLoggerPlugin = NetworkLoggerPlugin()
